package com.ics.top.batch.management.listener;


import com.ics.top.batch.management.service.BatchUserManagementLogClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/***
 *
 * Job执行监听器
 *
 * */
@Component
public class JobUserManagementListener extends JobExecutionListenerSupport {

	private static final Logger log = LoggerFactory.getLogger(JobUserManagementListener.class);
    @Autowired
    private BatchUserManagementLogClient batchUserManagementLogClient;

	@Override
	public void afterJob(JobExecution jobExecution) {
		//System.out.println("afterJob ..........is..........");
		log.info("JobExecution {}",jobExecution.toString());
        String batchLogsIdString =  jobExecution.getExitStatus().getExitCode();
        Long batchLogsId = 0L;
        log.info("日志id");
        if(batchLogsIdString != null && !"COMPLETED".equals(batchLogsIdString)){
            batchLogsId = Long.parseLong(batchLogsIdString);
        }
		if(jobExecution.getStatus() == BatchStatus.COMPLETED) {
            if(batchLogsId  > 0){
                batchUserManagementLogClient.update(batchLogsId,"SUCCESS");
            }
			log.info("!!! JOB 执行完成!");
		}else {
            batchUserManagementLogClient.update(batchLogsId,"FAILURE");
        }
	}

	/* (non-Javadoc)
	 * @see org.springframework.batch.core.listener.JobExecutionListenerSupport#beforeJob(org.springframework.batch.core.JobExecution)
	 */
	@Override
	public void beforeJob(JobExecution jobExecution) {
		System.out.println("beforeJob ......................");
		log.info("JobExecution {}",jobExecution.getAllFailureExceptions().toString());
		super.beforeJob(jobExecution);
	}
}
